package com.qitmiaojie.security.filter;

import com.qitmiaojie.security.filter.exception.KaptchaNotMatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前后端分离 验证码 filter
 */
public class LoginCodeFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    StringRedisTemplate redisTemplate;

    public static final String SPRING_SECURITY_FORM_Code = "code";

    private String code = SPRING_SECURITY_FORM_Code;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //判断是否post请求
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        //判断是否是json请求
        String code = request.getParameter("code");
        String key=request.getParameter("key");
        //2.获取 redis 获取验证码
        String redisCode = redisTemplate.opsForValue().get(key);
        if (!ObjectUtils.isEmpty(code) && !ObjectUtils.isEmpty(code) &&
                code.equalsIgnoreCase(redisCode)) {
            //3.获取用户名 和密码认证
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        redisTemplate.delete(key);
        throw new KaptchaNotMatchException("验证码不匹配!");
    }
}
